﻿#ifndef MQTTCLIENT_H
#define MQTTCLIENT_H

#include <QObject>
#include <qmqtt.h>


class MqttClient : public QObject
{
    Q_OBJECT

public:
    MqttClient(QObject *parent = nullptr);
    ~MqttClient();

    /**
     * @brief getServerIp 获取服务Ip
     */
    QString getServerIp() const;

    /**
     * @brief getServerPort 获取服务器端口
     */
    uint16_t getServerPort() const;

    /**
     * @brief getPublishTopics 获取发布主题
     * @return
     */
    QStringList getPublishTopics() const;

    /**
     * @brief getSubTopics 获取订阅主题
     * @return
     */
    QStringList getSubTopics() const;

public slots:
    /**
     * @brief publishMessage 发布消息
     * @param topic
     * @param message
     */
    void publishMessage(const QString& topic, const QByteArray& message);

private:
    /**
     * @brief loadConfig 加载mqtt配置
     * @param configPath mqtt配置文件
     */
    void loadConfig(const QString& configPath);

    /**
     * @brief initMQTT 初始化MQTT
     */
    void initMQTT();

private slots:
    /**
     * @brief OnConnected MQTT连接服务器成功
     */
    void OnConnected();

    /**
     * @brief OnDisconnected MQTT断开服务器连接
     */
    void OnDisconnected();

    /**
     * @brief OnError MQTT报错
     * @param error
     */
    void OnError(const QMQTT::ClientError error);

    /**
     * @brief OnSubscribed MQTT收到订阅成功
     * @param topic
     * @param qos
     */
    void OnSubscribed(const QString& topic, const quint8 qos = 0);

    /**
     * @brief OnUnsubscribed MQTT收到订阅失败
     * @param topic
     */
    void OnUnsubscribed(const QString& topic);

    /**
     * @brief OnPublished MQTT收到发布成功消息（服务器返回）qos=1的时候，服务器收到数据会返回
     * @param message
     * @param msgid
     */
    void OnPublished(const QMQTT::Message& message, quint16 msgid = 0);

    /**
     * @brief OnReceived MQTT收到订阅消息
     * @param message
     */
    void OnReceived(const QMQTT::Message& message);

    /**
     * @brief OnPingresp
     */
    void OnPingresp();

private:
    void testSend();

private:
    /**
     * @brief m_client MQTT客户端对象
     */
    QMQTT::Client *m_client;

    /**
     * @brief MQTT服务器的Ip和端口
     */
    QString m_serverIp;
    uint16_t m_serverPort;

    /**
     * @brief m_publishTopic 发布主题
     */
    QStringList m_publishTopics;

    /**
     * @brief m_subTopic  订阅主题列表
     */
    QStringList m_subTopics;

};
#endif // MQTTCLIENT_H
